package com.ship.dispatch.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.core.base.Page;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.SpDispatchScheme;
import com.ship.dispatch.bean.SpDispatchSchemeDetail;
import com.ship.dispatch.bo.HistoryDispatchBO;
import com.ship.dispatch.bo.SpDispatchSchemeDetailBO;
import com.ship.dispatch.bo.SpDispatchSchemeDetailTimeBo;
import com.ship.dispatch.model.SpDispatchSchemeSaveModel;
import com.ship.dispatch.model.dto.DispatchSchemeChartSaveDto;
import com.ship.dispatch.model.dto.SchemeChartSellDto;
import com.ship.dispatch.model.dto.SchemeChartSimpleDto;
import com.ship.dispatch.service.ExportService;
import com.ship.dispatch.service.SpDispatchSchemeDetailService;
import com.ship.dispatch.service.SpDispatchService;
import com.ship.dispatch.vo.SpDispatchSchemeDetailExVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.List;

import static com.ship.dispatch.util.NumberFormatUtil.decimalFormat;

/**
 * 调度优化 前端控制器
 *
 * @author AbyssRabbit@163.com
 * @since 2023-10-17
 */
@RestController
@RequestMapping("/spDispatch/")
@Api(value = "disSpDispatch", tags = "调度优化前端控制器")
public class SpDispatchController {

    @Autowired
    private SpDispatchService spDispatchService;

    @Autowired
    private SpDispatchSchemeDetailService detailService;

    @Autowired
    private ExportService exportService;

    /**
     * 手动同步船运合同、资源合同信息
     *
     * @return
     */
    @ApiOperation(value = "手动同步船运合同、资源合同信息")
    @GetMapping("contract/update")
    public JsonResult contractUpdate() {
        return detailService.contractUpdate();
    }

    /**
     * 新增调度方案信息
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "新增调度方案信息")
    @PostMapping("scheme/save")
    @Log(title = "新增调度方案信息",businessType = BusinessType.INSERT)
    public JsonResult schemeSave(@RequestBody SpDispatchSchemeSaveModel dto) {
        return detailService.schemeSave(dto);
    }


    /**
     * 获取调度优化方案甘特图信息
     *
     * @return
     */
    @ApiOperation(value = "获取调度优化方案甘特图信息")
    @PostMapping("scheme/chart")
    public JsonResult<SpDispatchSchemeDetail> getPlanSchemeChart(@RequestBody SchemeChartSimpleDto dto) {
        return spDispatchService.getPlanSchemeChart(dto);
    }

    /**
     * 调度方案绑定销售合同、补货
     *
     * @return
     */
    @ApiOperation(value = "调度方案绑定销售合同、补货")
    @PostMapping("scheme/sell")
    public JsonResult schemeSell(@RequestBody @Validated SchemeChartSellDto dto) {
        return spDispatchService.schemeSell(dto);
    }

    /**
     * 甘特图拖拽保存
     *
     * @return
     */
    @ApiOperation(value = "甘特图拖拽保存")
    @PostMapping("scheme/chart/save")
    public JsonResult schemeChartSave( @RequestBody @Validated DispatchSchemeChartSaveDto dto) {
        dto.setCreateBy(SecurityUtils.getStringUserId());
        return detailService.schemeChartSave(dto);
    }

    /**
     * 甘特图拖动关联信息计算保存
     *
     * @return
     */
    @ApiOperation(value = "甘特图拖动关联信息计算保存")
    @PostMapping("scheme/chart/calculate/save")
    public JsonResult schemeChartCalculateSave( @RequestBody @Validated DispatchSchemeChartSaveDto dto) {
        dto.setCreateBy(SecurityUtils.getStringUserId());
        return detailService.schemeChartCalculateSave(dto);
    }

    /**
     * 拖动实时计算前后空挡
     *
     * @return
     */
    @ApiOperation(value = "拖动实时计算前后空挡")
    @PostMapping("scheme/chart/calculate/time")
    public JsonResult<SpDispatchSchemeDetail> schemeChartCalculateTime(@RequestBody SpDispatchSchemeDetailTimeBo dto) {
        return spDispatchService.schemeChartCalculateTime(dto);
    }

    /**
     * 贸易利润率参数更改
     *
     * @param detail
     * @return
     */
    @ApiOperation(value = "贸易利润率参数更改")
    @PostMapping("tradingProfit/update")
    public JsonResult<SpDispatchSchemeDetail> tradingProfitUpdate(@RequestBody SpDispatchSchemeDetail detail) {
        return spDispatchService.tradingProfitUpdate(detail);
    }

    /**
     * 获取调度优化方案调度历史
     *
     * @return
     */
    @ApiOperation(value = "获取调度优化方案调度历史")
    @PostMapping("scheme/history")
    public JsonResult<List<SpDispatchSchemeDetail>> getSchemeHistory(@RequestBody HistoryDispatchBO historyDispatchBO) {
        return spDispatchService.getSchemeHistory(historyDispatchBO);
    }

    /**
     * 调度优化方案还原
     *
     * @return
     */
    @ApiOperation(value = "调度优化方案还原")
    @GetMapping("scheme/rollback/{schemeId}")
    @Log(title = "调度优化方案还原",businessType = BusinessType.UPDATE)
    public JsonResult schemeRollback(@PathVariable(value = "schemeId") String schemeId) {
        return spDispatchService.schemeRollback(schemeId);
    }

    /**
     * 根据方案详情ID获取变更历史记录
     *
     * @return
     */
    @ApiOperation(value = "根据方案详情ID获取变更历史记录")
    @PostMapping("scheme/detail/history")
    public JsonResult<List<SpDispatchSchemeDetail>> getSchemeDetailHistory(@RequestBody @Validated SchemeChartSimpleDto dto) {
        return spDispatchService.getSchemeDetailHistory(dto);
    }

    /**
     * 获取调度优化方案详情分页
     *
     * @return
     */
    @ApiOperation(value = "获取调度优化方案详情分页")
    @PostMapping("scheme/detail/page")
    public JsonResult<Object> getSchemeDetailPage(@RequestBody @Validated SpDispatchSchemeDetail dto) {
        return spDispatchService.getSchemeDetailPage(dto);
    }

    /**
     * 修改方案详情
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "修改方案详情")
    @PostMapping("scheme/detail/update")
    @Log(title = "修改方案详情",businessType = BusinessType.UPDATE)
    public JsonResult schemeDetailUpdate(@RequestBody SpDispatchSchemeDetailBO dto) {
        return detailService.schemeDetailUpdate(dto);
    }

    /**
     * 删除方案详情
     *
     * @param detailId
     * @param reasonMsg
     * @return
     */
    @ApiOperation(value = "删除方案详情")
    @DeleteMapping("scheme/detail/delete")
    @Log(title = "删除方案详情",businessType = BusinessType.DELETE)
    public JsonResult schemeDetailDelete(@RequestParam(value = "detailId") Long detailId, @RequestParam(value = "reasonMsg") String reasonMsg) {
        return detailService.schemeDetailDelete(detailId,reasonMsg);
    }



    @ApiOperation(value = "导出调度方案列表")
    @PostMapping("scheme/exportDispatchPlan")
    @Log(title = "导出调度方案列表",businessType = BusinessType.EXPORT)
    public JsonResult<Object> exportDispatchPlan(@RequestBody SpDispatchSchemeDetail dto) {
        //获取最新的方案信息
        SpDispatchScheme spDispatchScheme = spDispatchService.getBaseMapper().selectOne(
                new LambdaQueryWrapper<SpDispatchScheme>()
                        .eq(SpDispatchScheme::getIsHistory,0)
                        .eq(dto.getSchemeId() != null,SpDispatchScheme::getId,dto.getSchemeId())
                        .and(qw -> {
                            qw.eq(SpDispatchScheme::getCreateBy,SecurityUtils.getUsername());
                            qw.or().eq(SpDispatchScheme::getIsShare,1);
                        })
                        .orderByDesc(SpDispatchScheme::getCreateDate)
                        .last("limit 1")
        );
        if(spDispatchScheme == null){
            return JsonResult.success(new Page<>());
        }
        dto.setSchemeId(spDispatchScheme.getId());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scheme_id",spDispatchScheme.getId());
        if (CollectionUtil.isNotEmpty(dto.getIds())) {
            queryWrapper.in("id", dto.getIds());
        }
        queryWrapper.orderByDesc("voyage_no");
        List<SpDispatchSchemeDetail> exportList = detailService.pageExportList(dto, queryWrapper, new LinkedList<>());
        for (SpDispatchSchemeDetail spDispatchSchemeDetail : exportList) {
            if(spDispatchSchemeDetail.getIsFobSell() != null && spDispatchSchemeDetail.getIsFobSell().intValue() == 1){
                spDispatchSchemeDetail.setImo("");
                spDispatchSchemeDetail.setShipName("");
            }
            spDispatchSchemeDetail.setTradeBodyStr(spDispatchSchemeDetail.getTradeBodyStr());
            spDispatchSchemeDetail.setSellerTradeBodyStr(spDispatchSchemeDetail.getSellerTradeBodyStr());
            spDispatchSchemeDetail.setTradeTypeStr(spDispatchSchemeDetail.getTradeTypeStr());
            spDispatchSchemeDetail.setSellerTradeTypeStr(spDispatchSchemeDetail.getSellerTradeTypeStr());
            if (spDispatchSchemeDetail.getStorageCapacity() != null){
                String result = null;
                DecimalFormat decimalFormat = new DecimalFormat("#,###.###");
                result = decimalFormat.format(spDispatchSchemeDetail.getStorageCapacity());
                if(spDispatchSchemeDetail.getStorageCapacity() != null){
                    result = decimalFormat.format(spDispatchSchemeDetail.getStorageCapacity());
                    result = result+" m³";
                }
                spDispatchSchemeDetail.setStorageCapacityString(result);
            }

            if (spDispatchSchemeDetail.getLoadingCapacity() != null){
                String result = null;
                DecimalFormat decimalFormat = new DecimalFormat("#,###.###");
                if (spDispatchSchemeDetail.getLoadingCapacity()!=null){
                    result = decimalFormat.format(spDispatchSchemeDetail.getLoadingCapacity());
                    if(spDispatchSchemeDetail.getLoadingCapacityUnit() != null){
                        result = (result + (spDispatchSchemeDetail.getLoadingCapacityUnit().intValue() == 1 ? " MMBtu"
                                : (spDispatchSchemeDetail.getLoadingCapacityUnit().intValue() == 2 ? " m³" : " MT")));
                    }
                }
                spDispatchSchemeDetail.setLoadingCapacityString(result);
            }
        }
        Field[] fields = SpDispatchSchemeDetail.class.getDeclaredFields();
        String url = exportService.pageExport(exportList,fields,exportService.listStrByModuleAndUser
                ("sp_dispatch_scheme_detail",SecurityUtils.getUserId()), "调度优化方案详情信息");
        return JsonResult.success(url);
    }

    @ApiOperation(value = "导出调度方案列表")
    @PostMapping("scheme/exportDispatchPlanAndGante")
    public JsonResult<Object> exportDispatchPlanAndGante(@RequestBody SpDispatchSchemeDetailExVo spDispatchSchemeDetailExVo) {
        SpDispatchSchemeDetail dto = new SpDispatchSchemeDetail();
        dto.setIds(spDispatchSchemeDetailExVo.getIds());
        dto.setSeller(spDispatchSchemeDetailExVo.getSeller());

        //获取最新的方案信息
        SpDispatchScheme spDispatchScheme = spDispatchService.getBaseMapper().selectOne(
                new LambdaQueryWrapper<SpDispatchScheme>()
                        .eq(SpDispatchScheme::getIsHistory,0)
                        .and(qw -> {
                            qw.eq(SpDispatchScheme::getCreateBy,SecurityUtils.getUsername());
                            qw.or().eq(SpDispatchScheme::getIsShare,1);
                        })
                        .orderByDesc(SpDispatchScheme::getCreateDate)
                        .last("limit 1")
        );
        if(spDispatchScheme == null){
            return JsonResult.success(new Page<>());
        }
        dto.setSchemeId(spDispatchScheme.getId());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scheme_id",spDispatchScheme.getId());
        queryWrapper.orderByDesc("expected_loading_date");

        List<SpDispatchSchemeDetail> exportList = detailService.pageExportList(dto, queryWrapper, new LinkedList<>());
        for (SpDispatchSchemeDetail spDispatchSchemeDetail : exportList) {
            if(spDispatchSchemeDetail.getIsFobSell() != null && spDispatchSchemeDetail.getIsFobSell().intValue() == 1){
                spDispatchSchemeDetail.setImo("");
                spDispatchSchemeDetail.setShipName("");
            }
            spDispatchSchemeDetail.setTradeBodyStr(spDispatchSchemeDetail.getTradeBodyStr());
            spDispatchSchemeDetail.setSellerTradeBodyStr(spDispatchSchemeDetail.getSellerTradeBodyStr());
            spDispatchSchemeDetail.setTradeTypeStr(spDispatchSchemeDetail.getTradeTypeStr());
            spDispatchSchemeDetail.setSellerTradeTypeStr(spDispatchSchemeDetail.getSellerTradeTypeStr());
        }
        Field[] fields = SpDispatchSchemeDetail.class.getDeclaredFields();
        String fileUrl = exportService.pageExport(exportList,fields,exportService.listStrByModuleAndUser
                ("sp_dispatch_scheme_detail",SecurityUtils.getUserId()), "调度优化方案详情信息");
        String url = spDispatchService.exportDispatchPlanAndGante(spDispatchSchemeDetailExVo,fileUrl);
        return JsonResult.success(url);
    }

}
